﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using LyyCMS.Core.Models;
using LyyCommon;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;

namespace LyyCMS.Web.Areas.Dash.Controllers
{
    [Area("Dash")]
    [Route("Dash/[controller]/[action]")]
    public class BlogsController : BaseController
    {

        public BlogsController(ILogger<BaseController> loggger, LyyCMS.Core.LyyCMSEntities lyyCMSEntities) : base(loggger, lyyCMSEntities)
        {
        }

        public IActionResult Index(int page = 1)
        {

            //默认不加载 Comments数据， 注意 需要区分大小写,comments会报错

            List<Core.Models.Blog> blogswithcomment = _context.Blogs.
                Include("Comments")
                .OrderByDescending(x => x.Create_At)   //创建时间倒序
                .Skip((page - 1) * pagesize)         //截取数据
                .Take(pagesize)                      //取pagesize条数据
                .ToList();


            int count = 1; //总页数
            count = _context.Blogs.Count() / 5;
            count += _context.Blogs.Count() % 5 > 0 ? 1 : 0;

            ViewBag.pagecount = count;
            ViewBag.currentpage = page;

            ViewBag.preview = page > 1 ? page - 1 : page;
            ViewBag.nextpage = page >= count ? count : count + 1;

            return View(blogswithcomment);
        }

        public async Task<IActionResult> Details(int? id)
        {
            if (id == null)
            {
                return NotFound();
            }

            var blog = await _context.Blogs.FirstOrDefaultAsync(x => x.Id == id);

            if (blog == null)
            {
                return NotFound();
            }
            return View(blog);
        }

        public IActionResult Create()
        {
            return View();
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Create([Bind("Id,Title,Content,Category")] Blog blog)
        {
            base.GetSession(HttpContext);

            blog.Create_At = DateTime.Now;
            blog.Category = (BlogCategory)blog.Category;
            blog.UserId = session_uid;
            
            if (ModelState.IsValid)
            {
                _context.Add(blog);
                await _context.SaveChangesAsync();
                return RedirectToAction(nameof(Index));
            }
            return View(blog);
        }

        public async Task<IActionResult> Edit(int? id)
        {
            if (id == null)
            {
                return NotFound();
            }

            var blog =await _context.Blogs.FindAsync(id);
            if (blog == null)
            {
                return NotFound();
            }
            return View(blog);
        }


        public async Task<IActionResult> Edit(int id,[Bind("Id,Title,Content,Category")] Blog blog)
        {
            if (id != blog.Id)
            {
                return NotFound();
            }

            if (ModelState.IsValid)
            {
                try
                {
                    _context.Update(blog);
                    await _context.SaveChangesAsync();
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!BlogExists(blog.Id))
                    {
                        return NotFound();
                    }
                    else
                    {
                        throw;
                    }
                }
                return RedirectToAction(nameof(Index));
            }
            return View(blog);
        }

        public async Task<IActionResult> Delete(int? id)
        {
            if (id == null)
            {
                return NotFound();
            }
            var blog =await _context.Blogs
                .FirstOrDefaultAsync(x => x.Id == id);
            if (blog == null)
            {
                return NotFound();
            }

            return View(blog);
        }

        [HttpPost,ActionName("Delete")]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> DeleteConfirmed(int id)
        {
            var blog = await _context.Blogs.FindAsync(id);
            _context.Blogs.Remove(blog);
            await _context.SaveChangesAsync();
            return RedirectToAction(nameof(Index));

        }


        private bool BlogExists(int id)
        {
            return _context.Blogs.Any(x => x.Id == id);
        }
    }
}